package henu.innovation.utils;

import henu.innovation.entity.Exam;
import henu.innovation.service.ExamService;
import henu.innovation.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private ExamService examService;

    //    servlet中使用service所必须的内容!!!
    public void init(ServletConfig config) throws ServletException{
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext());
        super.init(config);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //得到要下载的文件名

        String fileName = request.getParameter("filename");
        System.out.println("filename:"+fileName);
        String examname = null;
        
        int examid;
        Exam exam;
        try{
            examid = Integer.parseInt(request.getParameter("examid"));
            exam = teacherService.teacherFindExam(examid);
            examname = exam.getName();
        }catch (Exception e){
            System.out.println("没有传examnid");
        }
        
        System.out.println("exnamea:" + examname);

//        fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");

        //上传的文件都是保存在/WEB-INF/upload目录下的子目录当中
        String fileSaveRootPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        //        处理文件名
//        fileSaveRootPath += "\\" + examname;
        System.out.println("下载路径：" + fileSaveRootPath);

        String realname = fileName.substring(fileName.indexOf("_") + 1);
        //得到要下载的文件
        System.out.println("realname:"+realname);

        File file = new File(fileSaveRootPath + File.separator + fileName);
        System.out.println("file"+file.getName());
        //如果文件不存在

        if (!file.exists()) {
            request.setAttribute("message", "您要下载的资源已被删除！！");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
        }


        //设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + "\"" + URLEncoder.encode(realname, "UTF-8") + "\"");
        //读取要下载的文件，保存到文件输入流
        FileInputStream fis = new FileInputStream(fileSaveRootPath + File.separator + fileName);
        //创建输出流
        OutputStream fos = response.getOutputStream();

        //设置缓存区
        OutputStream os = response.getOutputStream();

        //设置缓存区
        byte[] bytes = new byte[1024];
        while (fis.read(bytes) > 0) {
            os.write(bytes);
        }

        //关闭输入流
        fis.close();

        //关闭输出流
        fos.close();

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}